package com.ruoyi.product.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.ruoyi.product.domain.Mycomment;
import com.ruoyi.product.domain.PointMessage;
import com.ruoyi.product.service.IMycommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class MyListener {
    /**
     * 监听某个队列的消息
     * @param message 接收到的消息
     */
    @Autowired
    private IMycommentService mycommentService;

    @RabbitListener(queues = "item_queue")
    public void countPoint(PointMessage message, Message msg, Channel channel) throws IOException {
        System.out.println("消费者接收到的消息为：" + message);
        long msgTag = msg.getMessageProperties().getDeliveryTag();
        QueryWrapper<Mycomment> mycommentQueryWrapper = new QueryWrapper<>();
        mycommentQueryWrapper.eq("product_id",message.getPublishId());
        Mycomment mycomment = mycommentService.getOne(mycommentQueryWrapper);
        mycomment.setScoreNum(mycomment.getScoreNum()+message.getScore());
        boolean save = mycommentService.saveOrUpdate(mycomment);
        try {
            if (save) {
                //确认消息消费成功
                channel.basicAck(msgTag, false);
                log.info("积分获取成功！！！");
            }else {
                channel.basicReject(msgTag,true);
                log.error("积分获取失败！！！");
            }
        } catch (IOException e) {
            log.error("积分获取失异常！！！");
            channel.basicReject(msgTag,true);
        }
    }
}
